package com.itheima.task;

import com.itheima.common.constant.RedisConstant;
import com.itheima.common.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
@Slf4j
public class GarbageImage {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private AliOssUtil aliOssUtil;

    /**
     * 垃圾图片定时清理
     */
    @Scheduled(cron = "0 * * * * ?")
    public void deleteGarbageImage(){
        // 获取SetOperations
        SetOperations setOperations = redisTemplate.opsForSet();
        // 计算aliOssPicture和mysqlPicture两个集合的差值
        Set<String> difference = setOperations.difference(RedisConstant.SETMEAL_PIC_RESOURCES, RedisConstant.SETMEAL_PIC_DB_RESOURCES);
        // 删除阿里云存储的垃圾图片
        if (difference != null && difference.size() > 0){
            for (String s : difference) {
                log.info("删除垃圾照片，{}", s);
                // 获取文件名
                String objectName = s.substring(s.lastIndexOf("/") + 1);
                // 根据文件名删除文件
                aliOssUtil.delete(objectName);
                // 删除redis集合中垃圾图片的值
                redisTemplate.opsForSet().remove(RedisConstant.SETMEAL_PIC_RESOURCES, s);
            }
        }
    }
}
